package com.sh.test;

import com.sh.promise.IPromise;
import com.sh.promise.Promise;
import com.sh.promise.PromiseExecutor;
import com.sh.promise.PromiseHandler;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @Date 17:54 2023/3/9
 **/
public class SendMsgToBaidu {
    public static void main(String[] args) {
        IPromise promise = new Promise.Builder().promiseHandler(new PromiseHandler() {
            @Override
            public Object run(PromiseExecutor executor) throws Exception {
                //向百度发请求
                sendGet();
                return "成功";
            }
        }).build();
        promise.setSuccess("请求成功!");
        promise.addListener((resolvedData, e) -> {
            System.out.println("addListener = " + resolvedData);
        });
        System.out.println("promise.get() = " + promise.get());
    }

    public static String sendGet(){
        String url = "http://www.baidu.com";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        //System.out.println("Get："+httpGet.getURI());
        CloseableHttpResponse httpResponse = null;
        String content = "";
        try {
            httpResponse = httpClient.execute(httpGet);
            HttpEntity entity =httpResponse.getEntity();
            if(entity!=null) {
                //System.out.println("响应状态："+httpResponse.getStatusLine());
                System.out.println("百度 请求完成！！！！！");
                content = EntityUtils.toString(entity,"utf-8");
                //System.err.println("响应内容："+content);
                //System.out.println("内容长度："+content.length());
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(httpResponse!=null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content;
    }

}
